/**
 * @description websocket
 * @author 盘古他爹
 */

import * as WebSocket from "ws"
import { VerifyClientCallbackSync } from "ws"
import { Spider } from "../spider"
import { JwtWebSocket } from "../middleware/jwt.auth"
const jwtVerify: VerifyClientCallbackSync = (info) => {

    // let token = info.req.headers.authorization
    let token = info.req.headers["sec-websocket-protocol"]
    // console.log("req", info.req.headers);

    if (JwtWebSocket(token)) {
        info.req.headers.userInfo = JwtWebSocket(token)
    }
    return JwtWebSocket(token)
}
//创建ws的服务端对象
const ws = new WebSocket.Server({
    port: 8888,
    verifyClient: jwtVerify
})

import { readFileSync } from "fs"
const pic = "data:image/png;base64," + readFileSync("./example.png", { encoding: "base64" });
// console.log("pic", pic);

//对客户端连接事件进行监听
ws.on("connection", (client, req) => {
    // console.log("有客户端连接成功了", client)
    //对客户端连接对象进行message事件监听
    //msg: 由客户端发送给服务端的数据
    console.log(client.url);
    console.log("header", req.headers);

    console.log("req", req.headers.userInfo);
    const re = req
    // client.send(re) 
    client.send(pic)
    client.on("message", msg => {
        console.log("msg", msg.toString());
        // console.log("msg2", msg.url);
        client.send("尼玛")
    })

})

// ws.on("connection", (ws: any, request: any, client: any) => {

//     console.log("连接了", ws);
//     console.log("连接了2", request);
//     console.log("连接了3", client);

//     ws.on('message', function message(data: any) {
//         console.log(`Received message ${data} from user ${client}`);
//     });
// })









// ws.on('open', function open() {
//     const array = new Float32Array(5);

//     for (var i = 0; i < array.length; ++i) {
//         array[i] = i / 2;
//     }
//     // ws.emit()

//     // ws.send(array);
// });



// export {
//     ws
// }
